package com.seari.gena.ciosServer.handler;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.gena.bean.ServerBean;
import com.seari.utils.PropertiesUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import redis.clients.jedis.Jedis;

public class CIOSNotifyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
	
	protected static Logger logger = LoggerFactory.getLogger(CIOSNotifyClientHandler.class);
	
	private ServerBean bean;
	private String SID;
	public static Map<String,String> PowerSectionMap = new ConcurrentHashMap<String,String>();
	public static Map<String,String> FireAlarmMap = new ConcurrentHashMap<String,String>();
	public static Map<String,String> VentilationMap0 = new ConcurrentHashMap<String,String>();
	public static Map<String,String> VentilationMap1 = new ConcurrentHashMap<String,String>();
	public static Map<String,String> VentilationMap2 = new ConcurrentHashMap<String,String>();
	

	public CIOSNotifyClientHandler(ServerBean bean) {
		this.bean = bean;
	}

	/**
	 * 向服务端发送数据
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Jedis jedis = JedisUtilProxy.getJedis();
		logger.info("gena通知通道-开启：" + ctx.channel().localAddress() + "channelActive");
		bean.setNt("nt: gena:birth");

		String clientIP = bean.getCallback().split(":")[0];
		StringBuffer sb = new StringBuffer();
		String notify = new String();
		Properties prop = PropertiesUtil.loadConfig("genaLine8.properties");
		int FireAlarmLast = Integer.parseInt(prop.getProperty("FireAlarmLast"));
		int PowerSectionLast = Integer.parseInt(prop.getProperty("PowerSectionLast"));
		int VentilationLast = Integer.parseInt(prop.getProperty("VentilationLast"));

		if ("PowerSection".equals(bean.getSubscribe())) {
			//PowerSection
			String PowerStatus; //供电状态
			for(int i = (FireAlarmLast+1);i<=PowerSectionLast;i++){
				String value = jedis.hget("line_8", i+"");
				PowerSectionMap.put(i+"", value);
				if ("1".equals(value)) {
					PowerStatus = "Energized";// 供电
				} else  {
					PowerStatus = "Deenergized";// 断电
				}
				notify = "<?xml version=\"1.0\"?>"
						+ "<Envelope>"
						+ "<Body cls=\"PowerSection\" obj=\"" + prop.getProperty(i+"") + "\">"
						+ "<PowerStatus>" + PowerStatus + "</PowerStatus>"
						+ "</Body>"
						+ "</Envelope>";
				sb.append("NOTIFY / HTTP/1.1\r\n");
				sb.append("Host:" + clientIP + "\r\n");
				sb.append("Content-Length: " + notify.length() + "\r\n");
				sb.append(bean.getNt() + "\r\n");
				sb.append(bean.getSid() + "\r\n");
				sb.append("\r\n");
				sb.append(notify);
				logger.info("gena订阅发送的数据包：" + sb.toString());
				ctx.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
				sb.delete(0, sb.length());
			}

		} else if ("Ventilation".equals(bean.getSubscribe())) {
			// Ventilation
			String FanStatus = "Fault";//风机状态
			String FanDirection = "";// 风向 
			String status0 = "";
			String status1 = "";
			String status2 = "";
			for(int i = (PowerSectionLast+1);i<=VentilationLast;i=i+3){
				status0 = jedis.hget("line_8", String.valueOf(i));
				status1 = jedis.hget("line_8", String.valueOf(i+1));
				status2 = jedis.hget("line_8", String.valueOf(i+2));
				VentilationMap0.put(String.valueOf(i), status0);
				VentilationMap1.put(String.valueOf(i+1), status1);
				VentilationMap2.put(String.valueOf(i+2), status2);
				if("1".equals(status2) && "0".equals(status0) && "0".equals(status1)){
					FanStatus = "Off";
				}else if("0".equals(status2)){
					if("1".equals(status0) && "0".equals(status1)){
						FanStatus = "On";
						FanDirection = "Uptrack";
					}else if("0".equals(status0) && "1".equals(status1)){
						FanStatus = "On";
						FanDirection = "Downtrack";
					}else{
						FanDirection = "";
					}
				}
				
				notify = "<?xml version=\"1.0\"?>"
						+ "<Envelope>"
						+ "<Body cls=\"Ventilation\" obj=\"" + prop.getProperty(i+"") + "\">"
						+ "<FanStatus>" + FanStatus + "</FanStatus>"
						+ "</Body>"
						+ "</Envelope>";				
				sb.append("NOTIFY / HTTP/1.1\r\n");
				sb.append("Host:" + clientIP + "\r\n");
				sb.append("Content-Length: " + notify.length() + "\r\n");
				sb.append(bean.getNt() + "\r\n");
				sb.append(bean.getSid() + "\r\n");
				sb.append("\r\n");
				sb.append(notify);
				logger.info("gena订阅发送的数据包：" + sb.toString());
				ctx.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
				sb.delete(0, sb.length());
				
				notify = "<?xml version=\"1.0\"?>"
						+ "<Envelope>"
						+ "<Body cls=\"Ventilation\" obj=\"" + prop.getProperty(i+"") + "\">"
						+ "<FanDirection>" + FanDirection + "</FanDirection>"
						+ "</Body>"
						+ "</Envelope>";				
				sb.append("NOTIFY / HTTP/1.1\r\n");
				sb.append("Host:" + clientIP + "\r\n");
				sb.append("Content-Length: " + notify.length() + "\r\n");
				sb.append(bean.getNt() + "\r\n");
				sb.append(bean.getSid() + "\r\n");
				sb.append("\r\n");
				sb.append(notify);
				logger.info("gena订阅发送的数据包：" + sb.toString());
				ctx.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
				sb.delete(0, sb.length());
				
			}
			
		} else if ("FireAlarm".equals(bean.getSubscribe())) {
			//FireAlarm
			String AlarmStatus; //火警状态
			for(int i = 0;i<=FireAlarmLast;i++){
				String value = jedis.hget("line_8", i+"");
				FireAlarmMap.put(i+"", value);
				if ("1".equals(value)) {
					AlarmStatus = "On";// 
				} else  {
					AlarmStatus = "Off";// 
				}
				notify = "<?xml version=\"1.0\"?>"
						+ "<Envelope>"
						+ "<Body cls=\"FireAlarm\" obj=\"" + prop.getProperty(i+"") + "\">"
						+ "<AlarmStatus>" + AlarmStatus + "</AlarmStatus>"
						+ "</Body>"
						+ "</Envelope>";
				sb.append("NOTIFY / HTTP/1.1\r\n");
				sb.append("Host:" + clientIP + "\r\n");
				sb.append("Content-Length: " + notify.length() + "\r\n");
				sb.append(bean.getNt() + "\r\n");
				sb.append(bean.getSid() + "\r\n");
				sb.append("\r\n");
				sb.append(notify);
				logger.info("gena订阅发送的数据包：" + sb.toString());
				ctx.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
				sb.delete(0, sb.length());
			}
		}
		JedisUtilProxy.close(jedis);
		

	}

	/**
	 * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
	 *
	 */
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.info("gena通知通道-关闭：" + ctx.channel().localAddress() + "channelInactive");
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		logger.info("gena通知channelRead");
		ByteBuf buf = msg.readBytes(msg.readableBytes());
		String retunMsg = buf.toString(Charset.forName("UTF-8"));
		logger.info("通知返回报文：" + retunMsg);
	}

}